<template>
  <div class="d_main not">
    <div class="d_header">
      <div class="d_header_title">
        <div class="back pointer" @click="Back">
          <span class="el-icon-arrow-left"></span>
          <p>返回</p>
        </div>
        <h3>生产开单</h3>
      </div>
      <div class="d_header_btn">
        <div v-if="productList && productList.length > 0">
          <el-button
            v-show="productFrom.baseData.orderState === 3"
            type="danger"
            size="small"
            icon="el-icon-close"
            @click="allStop"
            v-permission="'MenuCode2-1-8'"
            >撤单停工</el-button
          >
          <el-button
            v-if="productFrom.baseData.produceState !== 2"
            type="success"
            size="small"
            icon="el-icon-check"
            @click="allFinish"
            v-permission="'MenuCode2-1-5'"
            >生产完成</el-button
          >
        </div>
      </div>
    </div>
    <div class="d_content">
      <el-form
        ref="orderForm"
        label-position="left"
        :model="productFrom"
        :rules="rules"
        class="orderForm"
      >
        <div class="d_content_left">
          <div class="d_orderDetails">
            <div class="item">
              <div class="cTitle">
                <h3>订单信息</h3>
              </div>
              <dl>
                <dt>订单单号</dt>
                <dd>{{ productFrom.baseData.xieYiShuHao || "--" }}</dd>
              </dl>
              <dl>
                <dt>订单类型</dt>
                <dd>{{ productFrom.baseData.orderTypeName || "--" }}</dd>
              </dl>
              <dl>
                <dt>客户单号</dt>
                <dd>{{ productFrom.baseData.customerBillNo || "--" }}</dd>
              </dl>
              <dl>
                <dt>合同号</dt>
                <dd>{{ productFrom.baseData.contractNo || "--" }}</dd>
              </dl>
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>产品信息</h3>
              </div>
              <dl>
                <dt>产品名称</dt>
                <dd>{{ productFrom.baseData.orderProductName || "--" }}</dd>
              </dl>
              <dl>
                <dt>产品板面</dt>
                <dd>{{ productFrom.baseData.printingSurface || "--" }}</dd>
              </dl>
              <dl>
                <dt>产品版本</dt>
                <dd>{{ productFrom.baseData.productVersions || "--" }}</dd>
              </dl>
              <dl>
                <dt>产品库存</dt>
                <dd>{{ productFrom.stockQuantity }}</dd>
              </dl>
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>业务信息</h3>
              </div>
              <dl>
                <dt>标签套数</dt>
                <dd>
                  {{ productFrom.baseData.taoZhuangQuantity || "--"
                  }}<span class="unit">{{
                    productFrom.baseData.taoZhuangQuantity ==
                    productFrom.baseData.tagSumQuantity
                      ? "枚"
                      : "套"
                  }}</span>
                </dd>
              </dl>
              <dl>
                <dt>标签枚数</dt>
                <dd>
                  {{ productFrom.baseData.tagSumQuantity || "--"
                  }}<span class="unit">枚</span>
                </dd>
              </dl>
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>数据信息</h3>
              </div>
              <dl>
                <dt>数据来源</dt>
                <dd>{{ productFrom.baseData.dataComeFromName || "--" }}</dd>
              </dl>
              <dl>
                <dt>数据数量</dt>
                <dd>{{ productFrom.baseData.tagDataQuantity || "--" }}</dd>
              </dl>
              <dl>
                <dt>数据状态</dt>
                <dd>{{ productFrom.baseData.dataProduceState || "--" }}</dd>
              </dl>
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>套装关系</h3>
              </div>
              <labelTree :tree-data="productFrom.packageRelations" />
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>产品包装</h3>
              </div>
              <dl>
                <dt>成品样式</dt>
                <dd>{{ productFrom.productData.productStyleName || "--" }}</dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle !== 1">
                <dt>出标方向</dt>
                <dd>{{ productFrom.productData.outDirectionName || "--" }}</dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle === 2">
                <dt>卷向</dt>
                <dd>
                  {{ productFrom.productData.scrollDirectionName || "--" }}
                </dd>
              </dl>
              <dl>
                <dt>贴标方式</dt>
                <dd>{{ productFrom.productData.tagAffixWayName || "--" }}</dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle === 2">
                <dt>卷芯大小</dt>
                <dd>
                  {{ productFrom.productData.mandrelSize || "--"
                  }}<span class="unit">mm</span>
                </dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle === 2">
                <dt>外直径不超过</dt>
                <dd>
                  {{ productFrom.productData.notOverDiameter || "--"
                  }}<span class="unit">mm</span>
                </dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle === 2">
                <dt>每卷等于</dt>
                <dd>
                  {{ productFrom.productData.pageEqualTags || "--"
                  }}<span class="unit">{{
                    productFrom.baseData.taoZhuangQuantity ==
                    productFrom.baseData.tagSumQuantity
                      ? "枚"
                      : "套"
                  }}</span>
                </dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle !== 2">
                <dt>每张等于</dt>
                <dd>
                  {{ productFrom.productData.pageEqualTags || "--"
                  }}<span class="unit">{{
                    productFrom.baseData.taoZhuangQuantity ==
                    productFrom.baseData.tagSumQuantity
                      ? "枚"
                      : "套"
                  }}</span>
                </dd>
              </dl>
              <dl v-if="productFrom.productData.productStyle !== 2">
                <dt>每包等于</dt>
                <dd>
                  {{ productFrom.productData.packageEqualPages || "--"
                  }}<span class="unit">张</span>
                </dd>
              </dl>
              <dl>
                <dt>每箱等于</dt>
                <dd>
                  {{ productFrom.productData.boxEqualPackages || "--"
                  }}<span class="unit">{{
                    productFrom.productData.productStyle !== 2 ? "包" : "卷"
                  }}</span>
                </dd>
              </dl>
              <dl>
                <dt>每箱共计</dt>
                <dd>
                  {{ productFrom.productData.boxEqualTags || "--"
                  }}<span class="unit">{{
                    productFrom.baseData.taoZhuangQuantity ==
                    productFrom.baseData.tagSumQuantity
                      ? "枚"
                      : "套"
                  }}</span>
                </dd>
              </dl>
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>订单备注</h3>
              </div>
              <div class="d_remark">
                {{ productFrom.baseData.orderRemark }}
              </div>
            </div>
            <div class="item">
              <div class="cTitle">
                <h3>其他信息</h3>
              </div>
              <dl>
                <dt>业务员</dt>
                <dd>{{ productFrom.baseData.salesmanName || "--" }}</dd>
              </dl>
              <dl>
                <dt>联系电话</dt>
                <dd>{{ productFrom.baseData.salesmanMobile || "--" }}</dd>
              </dl>
            </div>
          </div>
        </div>
        <div class="d_content_auto">
          <div class="left">
            <div class="title">
              <h3>生产列表</h3>
            </div>
            <div class="d_nrBox">
              <div class="d_orderList">
                <ul>
                  <li
                    v-for="item in productList"
                    :key="item.produceTaskBillNo"
                    :class="
                      item.produceTaskBillNo === selectItem.produceTaskBillNo
                        ? 'active'
                        : ''
                    "
                    @click="chsngeSelect(item)"
                  >
                    <div class="title not">
                      <h3>{{ item.produceTaskBillNo }}</h3>
                    </div>
                    <div class="tagBox">
                      <span>{{ item.produceBillTypeName }}</span>
                      <span :class="'color_' + item.taskProduceState">{{
                        item.taskProduceStateName
                      }}</span>
                    </div>
                    <div class="text">
                      <p>创建时间: {{ item.createDate }}</p>
                      <p>创建人: {{ item.createPersonName }}</p>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="d_btn">
              <el-button
                v-if="productFrom.baseData.produceState !== 2"
                size="small"
                icon="el-icon-plus"
                @click="addProduct"
                v-permission="'MenuCode2-1-1'"
                >新建生产单</el-button
              >
            </div>
          </div>
          <div class="content">
            <div class="title">
              <h3>生产明细</h3>
            </div>
            <!-- 操作区 S-->
            <div class="d_operationBox p16 pb0 mb0">
              <div class="d_btn">
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-download"
                  @click="print(selectItem)"
                  >下载工单</el-button
                >
              </div>
              <div class="d_btn">
                <template v-if="productFrom.baseData.orderState !== 2">
                  <el-button
                    v-if="
                      selectItem.taskProduceState === 1 &&
                      selectItem.produceBillState === 1
                    "
                    size="small"
                    icon="el-icon-document-delete"
                    v-permission="'MenuCode2-1-6'"
                    @click="stopOne(selectItem)"
                    >生产停工</el-button
                  >
                  <el-button
                    v-if="selectItem.produceBillState === 1"
                    size="small"
                    icon="el-icon-document-copy"
                    v-permission="'MenuCode2-1-7'"
                    @click="productCopy(selectItem)"
                    >生产补单</el-button
                  >
                  <!-- <el-button v-if="selectItem.taskProduceState === 0 && selectItem.produceBillState === 1" size="small" icon="el-icon-delete" @click="handleCancelCheck(selectItem)">作废</el-button> -->
                  <el-button
                    v-if="
                      selectItem.taskProduceState === 0 &&
                      selectItem.produceBillState === 1
                    "
                    size="small"
                    v-permission="'MenuCode2-1-10'"
                    @click="handleRevocatio(selectItem)"
                  >
                    <i class="iconfont recallIco mr5 f12" />撤回</el-button
                  >
                  <el-button
                    v-if="selectItem.produceBillState === 0"
                    size="small"
                    icon="el-icon-edit-outline"
                    v-permission="'MenuCode2-1-2'"
                    @click="editRow(selectItem)"
                    >编辑</el-button
                  >
                  <el-button
                    v-if="selectItem.produceBillState === 0"
                    size="small"
                    icon="el-icon-delete"
                    v-permission="'MenuCode2-1-3'"
                    @click="deleteRow(selectItem)"
                    >删除</el-button
                  >
                  <el-button
                    v-if="selectItem.produceBillState === 0"
                    type="primary"
                    size="small"
                    icon="el-icon-check"
                    v-permission="'MenuCode2-1-4'"
                    @click="configRow(selectItem)"
                    >确认</el-button
                  >
                </template>
              </div>
            </div>
            <!-- 操作区 E-->
            <div class="d_nrBox p16">
              <div class="cTitle mt0">
                <h3>拼版信息</h3>
              </div>
              <div class="dlText">
                <ol class="list list_3">
                  <dl>
                    <dt>版辊尺寸</dt>
                    <dd>
                      {{ selectItem.makeup_RollSize
                      }}<span class="unit">mm</span>
                    </dd>
                  </dl>
                  <dl>
                    <dt>数码板面</dt>
                    <dd>
                      {{ selectItem.makeup_DigitalEdition
                      }}<span class="unit">mm</span>
                    </dd>
                  </dl>
                  <dl>
                    <dt>跳距</dt>
                    <dd>
                      {{ selectItem.makeup_SkipDistance
                      }}<span class="unit">mm</span>
                    </dd>
                  </dl>
                  <dl>
                    <dt>间距</dt>
                    <dd>
                      {{ selectItem.makeup_SpaceBetween
                      }}<span class="unit">mm</span>
                    </dd>
                  </dl>
                  <dl>
                    <dt>拼版</dt>
                    <dd>{{ selectItem.makeup_Combine || "--" }}</dd>
                  </dl>
                  <dl>
                    <dt>模数</dt>
                    <dd>{{ selectItem.makeup_Modules || "--" }}</dd>
                  </dl>
                  <dl>
                    <dt>平张断张</dt>
                    <dd>{{ selectItem.makeup_PzDz || "--" }}</dd>
                  </dl>
                  <dl>
                    <dt>色数</dt>
                    <dd>{{ selectItem.makeup_Colors || "--" }}</dd>
                  </dl>
                  <dl>
                    <dt>计划成品米数</dt>
                    <dd>{{ selectItem.planCpMeters || "--" }}米</dd>
                  </dl>
                </ol>
              </div>
              <div class="cTitle">
                <h3>生产工艺</h3>
              </div>
              <div class="tableCon">
                <el-table
                  ref="multipleTable"
                  :data="selectItem.produceCraftList"
                  border
                  style="width: 100%"
                >
                  <el-table-column type="index" width="50" label="排序" />
                  <el-table-column
                    prop="produceCraft.produceCraftNo"
                    width="80"
                    label="工艺编号"
                  />
                  <el-table-column
                    prop="produceCraft.produceCraftName"
                    width="180"
                    label="工艺名称"
                  />
                  <el-table-column
                    prop="produceCraft.produceEquipmentName"
                    width="80"
                    label="工艺设备"
                  />
                  <el-table-column
                    prop="produceCraft.craftTaskPlanUseTime"
                    width="80"
                    label="计划工时"
                  />
                  <el-table-column
                    prop="produceCraft.craftTaskStateName"
                    width="80"
                    label="工艺状态"
                  >
                    <template slot-scope="scope">
                      <div class="flex">
                        <template
                          v-if="scope.row.produceCraft.craftTaskState === 2"
                        >
                          <span
                            class="mr5 spot"
                            style="background: #67c23a"
                          />{{ scope.row.produceCraft.craftTaskStateName }}
                        </template>
                        <template
                          v-else-if="
                            scope.row.produceCraft.craftTaskState === 1
                          "
                        >
                          <span
                            class="mr5 spot"
                            style="background: #3f61f1"
                          />{{ scope.row.produceCraft.craftTaskStateName }}
                        </template>
                        <template v-else>
                          <span
                            class="mr5 spot"
                            style="background: #999aaa"
                          />{{ scope.row.produceCraft.craftTaskStateName }}
                        </template>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="produceCraft.craftTaskRemark"
                    label="备注"
                  />
                </el-table>
              </div>
              <div class="cTitle">
                <h3>生产物料</h3>
              </div>
              <div class="tableCon">
                <el-table
                  ref="multipleTable"
                  :data="selectItem.produceMaterialList"
                  border
                  style="width: 100%"
                >
                  <el-table-column type="index" width="50" label="排序" />
                  <el-table-column
                    prop="goodsCode"
                    width="120"
                    label="物料编号"
                  />
                  <el-table-column
                    prop="goodsName"
                    width="160"
                    label="物料名称"
                  />
                  <el-table-column prop="stockGoodsName" label="规格型号" />
                  <el-table-column prop="categoryName" label="规格类型" />
                  <el-table-column
                    prop="planMaterialQuantity"
                    label="计划用料"
                  />
                  <el-table-column
                    prop="printMaterialQuantity"
                    label="打印用料"
                  />
                  <el-table-column prop="produceCraftName" label="使用工艺">
                    <template slot-scope="scope">
                      {{
                        scope.row.produceCraftName +
                        "/" +
                        scope.row.equipmentName
                      }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="getMaterialQuantity"
                    label="领料数量"
                  />
                  <el-table-column
                    prop="backMaterialQuantity"
                    label="退料数量"
                  />
                  <el-table-column prop="usedMaterialQuantity" label="实际用料">
                    <template slot-scope="scope">
                      <template
                        :class="
                          scope.row.usedMaterialQuantity >
                          scope.row.planMaterialQuantity
                            ? 'red'
                            : 'nomal'
                        "
                        class="flex"
                      >
                        {{ scope.row.usedMaterialQuantity }}
                      </template>
                    </template>
                  </el-table-column>
                  <el-table-column prop="produceMaterialRemark" label="备注" />
                </el-table>
              </div>
              <div class="cTitle">
                <h3>生产备注</h3>
              </div>
              <div class="d_remark">
                {{ selectItem.produceRemark || "暂无备注" }}
              </div>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <!-- 作废原因   -->
    <el-dialog
      :title="'原因'"
      :visible.sync="reasonVisible"
      :close-on-click-modal="false"
      custom-class="comDialog"
      append-to-body
      width="30%"
      @close="closeCancelDialog"
    >
      <div class="dialogDody">
        <el-form
          ref="cancelForm"
          :rules="cancelFormrules"
          :model="cancelForm"
          label-width="0px"
          class="dialogForm"
        >
          <el-form-item label="" prop="cancelReason">
            <el-input
              v-model="cancelForm.cancelReason"
              type="textarea"
              :autosize="{ minRows: 5 }"
              placeholder="请输入内容"
              size="mini"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="reasonVisible = false">取 消</el-button>
        <el-button
          :loading="addLableLoading"
          :disabled="addLableLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveReason"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 停工原因   -->
    <el-dialog
      :title="'原因'"
      :visible.sync="stopVisible"
      :close-on-click-modal="false"
      custom-class="comDialog"
      append-to-body
      width="30%"
      @close="closeStopDialog"
    >
      <div class="dialogDody">
        <el-form
          ref="cancelForm"
          :model="cancelForm"
          label-width="0px"
          class="dialogForm"
        >
          <el-form-item label="" prop="reason">
            <el-input
              v-model="cancelForm.stopWorkReason"
              type="textarea"
              :autosize="{ minRows: 5 }"
              placeholder="请输入内容"
              size="mini"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="stopVisible = false">取 消</el-button>
        <el-button
          :loading="addLableLoading"
          :disabled="addLableLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveStop"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <!-- 全部原因   -->
    <el-dialog
      :title="'原因'"
      :visible.sync="reasonVisibleall"
      :close-on-click-modal="false"
      custom-class="comDialog"
      append-to-body
      width="30%"
      @close="closeCancelDialogall"
    >
      <div class="dialogDody">
        <el-form
          ref="cancelForm"
          :model="cancelForm"
          label-width="0px"
          class="dialogForm"
        >
          <el-form-item label="" prop="reason">
            <el-input
              v-model="cancelForm.cancelReasonall"
              type="textarea"
              :autosize="{ minRows: 5 }"
              placeholder="请输入内容"
              size="mini"
              clearable
            />
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click="reasonVisible = false">取 消</el-button>
        <el-button
          v-loading="addLableLoading"
          :disabled="addLableLoading"
          element-loading-spinner="el-icon-loading"
          type="primary"
          size="mini"
          @click="saveReasonall"
          >保存</el-button
        >
      </div>
    </el-dialog>
    <rintT :product-from="prinftMass" :productdd="selectItem" />
  </div>
</template>
<script>
import SelectCraftlist from "@/components/selectCraft";
import SelectMateriaList from "@/components/selectMaterial";
import labelTree from "@/components/labelTree";
import { mapGetters } from "vuex";
import { uuid } from "vue-uuid";
import Sortable from "sortablejs";
import printJS from "print-js";
import PrintTemplate from "print-template";
import rintT from "./printT.vue";
import ElImageViewer from "element-ui/packages/image/src/image-viewer";
export default {
  name: "",
  components: {
    labelTree,
    SelectCraftlist,
    SelectMateriaList,
    ElImageViewer,
    rintT,
  },
  computed: {
    ...mapGetters(["userInfo", "name"]),
  },
  data() {
    return {
      orderInfos: {
        productData: {
          tagDataList: [{}, {}, {}],
        },
      },
      prinftMass: {},
      selectItem: {},
      cancelForm: {
        cancelReason: "",
        stopWorkReason: "",
        cancelReasonall: "",
      },
      selectArr: [],
      isShadeShow: false,
      reasonVisibleall: false,
      addLableLoading: false,
      urlList: [], // 图片列表
      showViewer: false, // 预览图片
      showOrder: false, // 订单弹窗
      showCraft: false, // 选择工艺
      showMateria: false, // 选择物料
      orderNo: "", // 订单号
      loading: null,
      conIndex: 0,
      tabsIndex: 0, // 右侧tabs切换索引
      tagIndex: 0, // 当前标签索引
      colorOps: "add", // 印刷颜色当前操作
      colorEditIndex: null, // 印刷颜色修改的索引
      dataLoading: false, // 订单详情数据加载
      orderLoading: false, // 订单保存加载效果
      isAddColor: false, // 印刷颜色新增弹框是否打开

      // 设置时间控件小于当前日期不能选择
      option: {
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 1 * 24 * 3600 * 1000;
        },
      },
      productFrom: {
        baseData: {},
        packageData: {},
        orderBaseData: {},
        productData: {},
      },
      isDisable: false, // 是否禁用输入框
      stopVisible: false,
      template: null,
      reasonVisible: false,
      typeStatus: 0,
      productList: [],
      cancelFormrules: {
        cancelReason: [
          { required: true, message: "请输入原因", trigger: "change" },
        ],
      },
      rules: {
        "productBase.customerName": [
          { required: true, message: "请选择客户", trigger: "change" },
        ],
        "productBase.productName": [
          {
            required: true,
            message: "请输入产品名称",
            trigger: ["change", "blur"],
          },
        ],
      },
    };
  },
  created() {
    // this.getTypeStatus()
    this.loading = this.$loading({
      lock: true,
      text: "数据加载中",
      spinner: "el-icon-loading",
      fullscreen: true,
      background: "rgba(0, 0, 0, 0.7)",
    });
    this.getOrderInfo();
  },
  deactivated() {
    // localStorage.removeItem('orderInit')
  },
  beforeDestroy() {
    // localStorage.removeItem('orderInit')
  },
  mounted() {},
  methods: {
    print(item) {
      this.prinftMass ={}
      this.prinftMass = this.productFrom;
      var printHtml = document.getElementById("print-iframe").innerHTML;
      var wind = window.open(
        "",
        "newwindow",
        " top=100, left=100, toolbar=no, menubar=no, scrollbars=no, resizable=no,location=n o, status=no"
      );
      wind.document.body.innerHTML = printHtml;
      wind.print();
      // const _div = this.$refs.printDiv
      // printJS({
      //   printable: _div,
      //   type: 'html',
      //   maxWidth: 200,
      //   scanStyles: false,
      //   headerStyle: 'font-weight: 600; font-size: 24px',
      //   targetStyles: ['*']
      // })
    },

    printpage(myDiv) {},
    addProduct() {
      this.$router.push({
        path: "/production/newproductionBilling", // 跳转的路径
        query: {
          orderNo: this.productFrom.baseData.orderNo,
          typeStatus: 0,
        },
      });
    },
    closeCancelDialog() {
      this.reasonVisible = false;
    },
    closeStopDialog() {
      this.stopVisible = false;
    },
    closeCancelDialogall() {
      this.reasonVisibleall = false;
    },
    allStop() {
      this.$confirm("点击撤单停工后, 不可在对订单下的生产单进行编辑?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.product
          .ExcuteCancelProduceBillAndStopWork({
            saleOrderNo: this.productFrom.baseData.orderNo,
          })
          .then((res) => {
            this.$message({
              type: "success",
              message: "成功!",
            });
            this.reasonVisibleall = false;
            this.getOrderInfo()
          })
          .catch(() => {});
      });
    },
    // 停工
    stopOne(item) {
      this.cancelForm.stopWorkReason = "";
      this.stopVisible = true;
    },
    // 作废
    handleCancelCheck(row) {
      this.cancelForm.cancelReason = "";
      this.reasonVisible = true;
    },
    saveReasonall() {
      this.$api.product
        .SetOrdersProduceBillsStop({
          saleOrderNo: this.productFrom.baseData.orderNo,
          stopWorkReason: this.cancelForm.cancelReasonall,
        })
        .then((res) => {
          this.$message({
            type: "success",
            message: "成功!",
          });
          this.reasonVisibleall = false;
          this.getTabIndexInfo();
        })
        .catch(() => {});
    },
    // 停工
    saveStop() {
      this.$api.product
        .StopProduceTaskBill({
          produceTaskID: this.selectItem.produceTaskID,
          cancelReason: this.selectItem.stopWorkReason,
        })
        .then((res) => {
          this.stopVisible = false;
          this.getTabIndexInfo();
        })
        .catch(() => {});
    },
    allFinish() {
      this.$api.product.JuadgeSaleOrderProduceIsFinished({saleOrderNo:this.productFrom.baseData.orderNo}).then((res) => {
        if (res.isHaveProduceTasks) {
          this.$message.warning("该订单下有未完成生产单，请先完成");
          return
        } else {
          this.$confirm(
            "生产完成后该订单不能在新建、编辑生产单是否确定?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            this.$api.product
              .ExcuteSureSaleOrderProduceFinished({
                saleOrderNo: this.productFrom.baseData.orderNo,
              })
              .then((res) => {
                this.$message({
                  type: "success",
                  message: "确认成功!",
                });
                this.getTabIndexInfo();
              })
              .catch(() => {});
          });
        }
      });
    },
    // 报废
    saveReason() {
      this.$refs.cancelForm.validate((valid) => {
        if (valid) {
          this.$api.product
            .CancelProduceTaskBill({
              produceTaskID: this.selectItem.produceTaskID,
              cancelReason: this.selectItem.cancelReason,
            })
            .then((res) => {
              this.reasonVisible = false;
              this.getTabIndexInfo();
            })
            .catch(() => {});
        }
      });
    },
    // 生产补单
    productCopy(item) {
      this.$router.push({
        path: "/production/newproductionBilling", // 跳转的路径
        query: {
          produceTaskBillNo: item.produceTaskBillNo,
          typeStatus: 4,
        },
      });
    },
    // 撤回
    handleRevocatio(item) {
      this.$api.product
        .RevocationProduceTaskBill({
          produceTaskID: item.produceTaskID,
        })
        .then((res) => {
          this.$message({
            type: "success",
            message: "撤回成功!",
          });
          this.getTabIndexInfo();
        })
        .catch(() => {});
    },
    // 确认
    configRow(item) {
      const parmas = {
        produceTaskID: item.produceTaskID,
      };
      this.$api.product
        .SureProduceTaskBill(parmas)
        .then((res) => {
          this.$message({
            type: "success",
            message: "确认成功!",
          });
          this.getTabIndexInfo();
        })
        .catch(() => {});
    },
    // 编辑
    editRow(item) {
      this.$router.push({
        path: "/production/newproductionBilling", // 跳转的路径
        query: {
          produceTaskBillNo: item.produceTaskBillNo,
          produceTaskID: item.produceTaskID,
          typeStatus: 2,
        },
      });
    },
    // 删除
    deleteRow(item) {
      this.$confirm("是否删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$api.product
          .DeleteProduceTaskBill({
            produceTaskID: item.produceTaskID,
          })
          .then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.$router.go(0);
            this.getTabIndexInfo();
          })
          .catch(() => {});
      });
    },

    chsngeSelect(item) {
      this.selectItem = item;
    },
    getTabIndexInfo() {
      const parmas = {
        saleOrderNo: this.productFrom.baseData.orderNo,
      };
      this.$api.product
        .GetProduceTaskBillsForOrder(parmas)
        .then((res) => {
          this.productList = res;
          console.log(res);
          if (res.length > 0) {
            this.selectItem = this.productList[0];
          } else {
            this.selectItem.produceCraftList = [];
            this.selectItem.produceMaterialList = [];
            this.selectItem = this.productList[0];
          }

          this.loading.close();
        })
        .catch(() => {
          this.loading.close();
        });
    },
    getOrderInfo() {
      const parmas = {
        saleOrderID: this.$route.query.orderID,
        saleOrderNo: this.$route.query.saleOrderNo,
      };
      this.$api.business
        .GetSaleOrderDetail(parmas)
        .then((res) => {
          this.prinftMass = res;
          this.productFrom = res;
          this.getTabIndexInfo();

          // this.showColorDrafts()
          this.loading.close();
        })
        .catch(() => {
          this.loading.close();
        });
    },
    getTypeStatus() {
      this.typeStatus = Number(this.$route.query.typeStatus);
      if (Number(this.$route.query.typeStatus) === 0) {
        this.getOrderDetail();
      } else if (Number(this.$route.query.typeStatus) === 1) {
        this.isDisable = true;
        this.getTaskBillDetail();
      } else if (Number(this.$route.query.typeStatus) === 2) {
        this.getTaskBillDetail();
      } else if (Number(this.$route.query.typeStatus) === 3) {
        this.isDisable = true;
        this.getTaskBillDetail();
      } else if (Number(this.$route.query.typeStatus) === 4) {
        this.getCreateProduceTaskBill();
      } else if (Number(this.$route.query.typeStatus) === 5) {
        this.getCopyOrderDetail();
      }
    },
    selectshowMateria() {
      if (
        this.productFrom.produceCraftList.length <= 0 &&
        this.isDisable !== true
      ) {
        this.$message({
          type: "error",
          message: "请先选择生产工艺!",
        });
        return;
      } else {
        this.showMateria = true;
        // this.productFrom.produceMaterialList.forEach(e => {
        //   e.craftTaskClientNo = ''
        // })
      }
    },
    // 右侧tab切换
    tabChange(index) {
      if (index === 1) {
        if (
          this.productFrom.produceCraftList.length <= 0 &&
          this.isDisable !== true
        ) {
          this.$message({
            type: "error",
            message: "请先选择生产工艺!",
          });
          return;
        } else {
          // this.productFrom.produceMaterialList.forEach(e => {
          //   e.craftTaskClientNo = ''
          // })
        }
      }
      this.fillSelect();
      this.tabsIndex = index;
    },
    selectChange(index) {
      this.conIndex = index;
    },
    //
    changDviesAndCraf() {
      // this.fillSelect()
    },
    // 预览彩稿
    previewColor(url) {
      this.isShadeShow = true;
      this.colorImagUrl = url;
    },
    getName(arr, code) {
      let name = "";
      arr.forEach((e) => {
        if (e.equipmentCode === code) {
          name = e.equipmentName;
        }
      });
      return name;
    },
    fillSelect() {
      const _selectArr = [];
      for (
        let index = 0;
        index < this.productFrom.produceCraftList.length;
        index++
      ) {
        const _a = {};
        _a.craftTaskClientNo =
          this.productFrom.produceCraftList[
            index
          ].produceCraft.craftTaskClientNo;
        _a.name =
          this.productFrom.produceCraftList[index].produceCraft
            .produceCraftName +
          "/" +
          this.getName(
            this.productFrom.produceCraftList[index].craftEquipments,
            this.productFrom.produceCraftList[index].produceCraft
              .produceEquipment
          );
        // this.productFrom.produceCraftList[
        //   index
        // ].produceCraft.craftTaskClientNo = _a.craftTaskClientNo
        _selectArr.push(_a);
      }
      this.selectArr = _selectArr;
    },
    // 获取订单详情
    getOrderDetail() {
      const parmas = {
        saleOrderNo: this.$route.query.orderNo,
      };
      this.$api.product
        .AutoCreateProduceTaskBill(parmas)
        .then((res) => {
          this.productFrom = res;
          this.showColorDrafts();
          this.loading.close();
        })
        .catch(() => {
          this.loading.close();
        });
    },
    // 根据老生产单复制创建新的生产任务单
    getCreateProduceTaskBill() {
      const parmas = {
        produceTaskBillNo: this.$route.query.produceTaskBillNo,
      };
      this.$api.product
        .CopyCreateProduceTaskBill(parmas)
        .then((res) => {
          this.productFrom = res;
          this.showColorDrafts();
          this.loading.close();
        })
        .catch(() => {
          this.loading.close();
        });
    },
    // 生产任务单明细数据
    getTaskBillDetail() {
      const parmas = {
        produceTaskBillNo: this.$route.query.produceTaskBillNo,
        produceTaskID: this.$route.query.produceTaskID,
      };
      this.$api.product
        .GetProduceTaskBillDetail(parmas)
        .then((res) => {
          this.productFrom = res;
          this.showColorDrafts();
          res.produceCraftList.forEach((n) => {
            n.produceCraft.craftTaskClientNo = n.produceCraft.craftTaskClientNo
              ? n.produceCraft.craftTaskClientNo
              : uuid.v4();
          });
          res.produceMaterialList.forEach((e) => {
            res.produceCraftList.forEach((n) => {
              if (n.produceCraft.craftTaskNo === e.craftTaskNo) {
                n.produceCraft.craftTaskClientNo = e.craftTaskClientNo;
                this.selectArr.push({
                  name:
                    n.produceCraft.produceCraftName +
                    "/" +
                    this.getName(
                      n.craftEquipments,
                      n.produceCraft.produceEquipment
                    ),
                  craftTaskClientNo: e.craftTaskClientNo,
                });
              }
            });
          });
          this.loading.close();
        })
        .catch(() => {
          this.loading.close();
        });
    },
    // 复制
    getCopyOrderDetail() {
      const parmas = {
        saleOrderNo: this.$route.query.saleOrderNo,
      };
      const parmast = {
        produceTaskBillNo: this.$route.query.produceTaskBillNo,
        produceTaskID: this.$route.query.produceTaskID,
      };
      this.$api.product
        .AutoCreateProduceTaskBill(parmas)
        .then((copy) => {
          this.$api.product
            .GetProduceTaskBillDetail(parmast)
            .then((info) => {
              info.baseData.produceTaskID = copy.baseData.produceTaskID;
              info.produceCraftList.forEach((n) => {
                n.produceCraft.craftTaskClientNo = n.produceCraft
                  .craftTaskClientNo
                  ? n.produceCraft.craftTaskClientNo
                  : uuid.v4();
              });
              info.produceMaterialList.forEach((e) => {
                info.produceCraftList.forEach((n) => {
                  if (n.produceCraft.craftTaskNo === e.craftTaskNo) {
                    n.produceCraft.craftTaskClientNo = e.craftTaskClientNo;
                    this.selectArr.push({
                      name:
                        n.produceCraft.produceCraftName +
                        "/" +
                        this.getName(
                          n.craftEquipments,
                          n.produceCraft.produceEquipment
                        ),
                      craftTaskClientNo: e.craftTaskClientNo,
                    });
                  }
                });
              });
              this.productFrom = info;
              this.showColorDrafts();
              this.loading.close();
            })
            .catch(() => {
              this.loading.close();
            });
        })
        .catch(() => {
          this.loading.close();
        });
    },
    onCloseviewer() {
      this.isShadeShow = false;
    },
    showColorDrafts() {
      const parmas = {
        orderNo: this.productFrom.orderBaseData.orderNo,
      };
      this.$api.product
        .QueryOrdersColorDrafts(parmas)
        .then((res) => {
          if (res.fileDataList && res.fileDataList.length) {
            const ur = [];
            res.fileDataList.forEach((e) => {
              ur.push(e.draftFilePreviewUrl);
            });
            this.$nextTick(() => {
              this.urlList = ur;
              // this.showViewer = true
            });
          } else {
            // this.$message({
            //   type: 'error',
            //   message: '--彩稿'
            // })
          }
        })
        .catch(() => {});
    },
    // 选择订单
    selectCurrentRow() {},
    // 确认订单
    confirmOrder() {
      const parmas = {
        produceTaskID: this.productFrom.baseData.produceTaskID,
      };
      this.$api.product
        .SureProduceTaskBill(parmas)
        .then((res) => {
          this.$router.go(-1);
        })
        .catch(() => {});
    },
    // 选择工艺
    refuseListsAll(val) {
      const parmas = {
        craftCodes: [],
      };
      val.forEach((i) => {
        parmas.craftCodes.push(i.code);
      });
      this.$api.product
        .SureChooseProduceCraftEquipmentMaps(parmas)
        .then((res) => {
          const _data = [];
          res.forEach((e) => {
            const _ar = {
              produceCraft: {},
              craftEquipments: [],
            };
            _ar.produceCraft.produceCraftName = e.craftName;
            _ar.produceCraft.produceCraftNo = e.craftCode;
            _ar.produceCraft.craftTaskClientNo = uuid.v4();
            _ar.produceCraft.craftTaskPlanUseTime = 0;
            _ar.produceCraft.craftTaskRemark = "";
            _ar.craftEquipments = e.craftEquipments;
            _ar.produceCraft.produceEquipment =
              e.craftEquipments[0].equipmentCode;
            _ar.produceCraft.produceEquipmentName =
              e.craftEquipments[0].equipmentName;
            _data.push(_ar);
          });
          _data.forEach((e) => {
            this.productFrom.produceCraftList.push(e);
          });
        })
        .catch(() => {});
    },
    // 选择物料
    refuseListsMateriAll(val) {
      const _data = [];

      val.forEach((e) => {
        const _ar = {
          goodsName: "",
          stockGoodsCode: "",
          stockGoodsName: "",
          specificationName: "",
          categoryName: "",
          planMaterialQuantity: 0,
          produceMaterialRemark: "",
        };
        _ar.stockGoodsCode = e.stockGoodsCode;
        _ar.stockGoodsName = e.stockGoodsName;
        _ar.goodsName = e.goodsName;
        _ar.specificationName = e.specificationName;
        _ar.categoryName = e.categoryName;
        _ar.stockSumQuantity = e.stockSumQuantity;
        _data.push(_ar);
      });
      _data.forEach((e) => {
        this.productFrom.produceMaterialList.push(e);
      });
    },
    // 删除工艺
    craftDelete(cl, index) {
      this.$confirm("是否删除该工艺?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        const _status = this.productFrom.produceMaterialList.some(
          (item) => item.craftTaskClientNo === cl.produceCraft.craftTaskClientNo
        );
        if (_status) {
          this.$message({
            type: "error",
            message: "有引用的生产物料，请先删除!",
          });
          return;
        } else {
          this.productFrom.produceCraftList.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        }
      });
    },
    // 删除物料
    matairDelete(index) {
      this.$confirm("是否删除该物料?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.productFrom.produceMaterialList.splice(index, 1);
        this.$message({
          type: "success",
          message: "删除成功!",
        });
      });
    },
    setSort() {
      const el = document.getElementById("dragList");
      Sortable.create(el, {
        ghostClass: "sortable-ghost", // 放置占位符的类名
        onUpdate: (evt) => {
          const targetRow = this.productFrom.produceCraftList.splice(
            evt.oldIndex,
            1
          )[0];
          this.productFrom.produceCraftList.splice(evt.newIndex, 0, targetRow);
          const newArray = this.productFrom.produceCraftList.slice(0);
          this.productFrom.produceCraftList = [];
          newArray.forEach((m, x) => {
            m.produceCraft.produceCraftSort = x;
          });
          this.$nextTick(() => {
            this.productFrom.produceCraftList = newArray;
          });
        },
      });
    },

    // 开单保存
    saveOrder() {
      const _data = {};
      const productTagCodes = [];
      const produceMaterials = [];
      const produceCrafts = [];
      const {
        outDirectionName,
        productStyleName,
        scrollDirectionName,
        tagAffixWayName,
        ..._producePackage
      } = this.productFrom.packageData;
      _producePackage.saleOrderNo = this.productFrom.orderBaseData.orderNo;
      this.productFrom.orderTagDataList.forEach((e) => {
        productTagCodes.push(e.productTagCode);
      });
      this.productFrom.produceMaterialList.forEach((e) => {
        const _mater = {
          stockGoodsCode: "",
          planUseQuantity: 0,
          materialRemark: "",
        };
        _mater.stockGoodsCode = e.stockGoodsCode;
        _mater.planUseQuantity = Number(e.planMaterialQuantity);
        _mater.materialRemark = e.produceMaterialRemark;
        _mater.craftTaskClientNo = e.craftTaskClientNo || "";
        produceMaterials.push(_mater);
      });
      this.productFrom.produceCraftList.forEach((e) => {
        // eslint-disable-next-line no-unused-vars
        const { produceCraftName, ...carft } = e.produceCraft;
        produceCrafts.push(carft);
      });
      _data.produceTaskID = this.productFrom.baseData.produceTaskID;
      _data.makeup_RollSize = Number(this.productFrom.baseData.makeup_RollSize);
      _data.makeup_DigitalEdition = Number(
        this.productFrom.baseData.makeup_DigitalEdition
      );
      _data.makeup_SkipDistance = Number(
        this.productFrom.baseData.makeup_SkipDistance
      );
      _data.makeup_SpaceBetween = Number(
        this.productFrom.baseData.makeup_SpaceBetween
      );
      _data.makeup_Combine = this.productFrom.baseData.makeup_Combine;
      _data.makeup_Modules = this.productFrom.baseData.makeup_Modules;
      _data.makeup_PzDz = this.productFrom.baseData.makeup_PzDz;
      _data.makeup_Colors = this.productFrom.baseData.makeup_Colors;
      _data.produceRemark = this.productFrom.baseData.produceRemark;
      _data.producePackage = _producePackage;
      _data.productTagCodes = productTagCodes;
      _data.produceMaterials = produceMaterials;
      _data.produceCrafts = produceCrafts;

      for (let index = 0; index < produceCrafts.length; index++) {
        if (produceCrafts[index].produceEquipment === "") {
          this.$message({
            type: "error",
            message: "请选择生产工艺下的设备名称!",
          });
          return;
        }
      }
      for (let index = 0; index < produceCrafts.length; index++) {
        if (produceCrafts[index].craftTaskPlanUseTime === "") {
          this.$message({
            type: "error",
            message: "请输入计划工时!",
          });
          return;
        }
      }
      for (let index = 0; index < produceMaterials.length; index++) {
        if (produceMaterials[index].craftTaskClientNo === "") {
          this.$message({
            type: "error",
            message: "请选择生产物料下的生产工艺!",
          });
          return;
        }
      }
      for (let index = 0; index < produceMaterials.length; index++) {
        if (produceMaterials[index].planUseQuantity === "") {
          this.$message({
            type: "error",
            message: "请输入计划用料!",
          });
          return;
        }
      }
      this.$api.product
        .ExcuteUpdateProduceTaskBill(_data)
        .then((res) => {
          this.$router.go(-1);
        })
        .catch(() => {});
    },
    // 控制标签内容层显示隐藏
    shrink(item) {
      this.$set(item, "isShow", !item.isShow);
    },
    // 计算产品包装，每箱共计多少枚
    getBoxEqualTags() {
      const pageEqualTagsNum = Number(
        this.productFrom.packageData.pageEqualTags
      );
      const packageEqualPagesNum = Number(
        this.productFrom.packageData.packageEqualPages
      );
      const boxEqualPackagesNum = Number(
        this.productFrom.packageData.boxEqualPackages
      );
      if (this.productFrom.packageData.productStyle !== 2) {
        this.productFrom.packageData.boxEqualTags =
          pageEqualTagsNum * packageEqualPagesNum * boxEqualPackagesNum;
      } else {
        this.productFrom.packageData.boxEqualTags =
          pageEqualTagsNum * boxEqualPackagesNum;
      }
    },
    // 初始化订单数据
    getInitOrder(oldOrderNo) {},
    // 返回
    Back() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
</style>
<style lang="scss">
.el-loading-mask {
  top: 0;
}
</style>
